<template>
  <div class="app-container legal-wrap">
    <dynamic-legal-create
      ref="dynamicLegal"
      v-model="legalParam"
      :hide-required-asterisk="false"
      :rules="rules"
      :default-list="defaultList"
      :constructions="comLegalConstruction"
      :flow-structure="processDetail"
      :last-template="lastTemplate"
      :download-loading="downloadLoading"
      @downloadTemplate="downloadTemplate"
      @showPreviewDrawer="showPreviewDrawer"
      @showTemplateDrawer="showTemplateDrawer"
    />
    <!-- 关联账号 -->
    <LinkedAccount ref="linkedAccountRef" v-model="legalParam.accountList" :loading="queryAccountLoading" show-add-btn show-del-btn />
    <!-- 关联合同 -->
    <ContractRelevance ref="contractRelevanceRef" v-model="legalParam.contractList" section-title="关联合同" />
    <audit-process
      ref="auditProcess"
      :default-aduitor-list="[proposer]"
      :old-audit-info="legalDetail.oldAduitInfo"
      v-model="legalParam.aduitInfo"
      :flow-structure="processDetail"
      :is-modify="Boolean(remodifyId)"
      :disable="Boolean(remodifyId)"
      :is-modify-form="Number(isModifyForm)"
      :current-process-index="Number(currentProcessIndex)"
      @submit="submitFun"
      @getProcess="getProcess"
    />
    <fixed-pagination>
      <div class="center">
        <el-button v-if="!legalId" type="info" size="small" class="back-btn empty-btn-style" @click="toBackStep">上一步</el-button>
        <el-button v-if="setSubmitStatus()" type="primary" size="small" class="submit-btn flex-center" @click="submit()">
          <div class="flex-center">
            发起审批
            <tipIcon v-if="signUpId" is-btn-tip class="ml5" content="发起合同审批后，请返回签约内审进行后续操作"/>
          </div>
        </el-button>
        <el-button v-if="setSaveDraftStatus()" type="info" size="small" class="back-btn empty-btn-style" @click="saveDraft">保存草稿</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">返回列表</el-button>
      </div>
    </fixed-pagination>
    <ContractTemplate
      ref="contractTemplateRef"
      :contract-type="type"
      :preview-path="previewPath"
      :download-loading="downloadLoading"
      @downloadTemplate="downloadTemplate" />
    <ContractPreview
      ref="ContractPreviewRef"
      :file-data="lastTemplate"
      :preview-path="previewPath"
      :download-loading="downloadLoading"
      :show-footer="false"
      is-fill
      @setDownloadParams="downloadPreviewFile"/>
  </div>
</template>
<script>
import DynamicLegalCreate from '../module/dynamicLegalCreate';
import ContractRelevance from '../module/contractRelevance';
import LinkedAccount from '@/components/legal/linkedAccount';
import AuditProcess from '@/components/Common/auditProcess';
import SectionTitle from '@/components/Title';
import ContractTemplate from '@/components/legal/contractTemplate/index';
import ContractPreview from '@/components/legal/contractTemplate/contractPreview';
import Common from '../mixins/common';
import { kolLegalConstruct as legalConstruction } from '../model/legalConstruction';
import { kolLegalRules } from '../model/legalRules';
import { signUpDetail } from '@/api/signUp';
import { getResourceListPost } from '@/api/resource';
import math from '@/utils/math';
import { plateformType } from '@/views/signUp/components/status';
import { platformOptions } from '../../module/options';
import { getExplorer } from '@/utils/tools';

export default {
  name: 'KolLegal',
  components: {
    DynamicLegalCreate,
    AuditProcess,
    SectionTitle,
    ContractTemplate,
    ContractPreview,
    ContractRelevance,
    LinkedAccount
  },
  mixins: [
    Common
  ],
  props: {
    legalDetail: {
      type: Object | String,
      default: () => null
    },
    type: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      kolLegalRules,
      legalParam: {
        createInfo: {
          createrDepartment: '',
          creater: '',
          createrPost: '',
          createrId: '',
          createrDepartmentId: '',
          proposer: null,
          proposerId: '',
          proposerAvatar: '',
          departmentId: '',
          post: '--',
          flowCode: ''
        },
        contractInfo: {
          type: '',
          name: '',
          tempSource: '',
          subject: '',
          oppCompany: '',
          signType: '',
          code: '',
          describe: '',
          deadline: '',
          otherDec: '',
          attachment: [],
          cooperNature: '',
          oppIdentity: '',
          accountPeriod: {
            type: 1,
            name: ''
          },
          cooperModel: {
            type: '',
            name: ''
          },
          cooperPlatforms: [{
            type: '',
            name: '',
            account: ''
          }],
          earnings: {
            proportion: '',
            guaranteeSum: '',
            earningTypes: [1]
          },
          // contractCodes: [{ code: '' }],
          ourStamp: '',
          legalTemplate: '',
          rebates: '', // 销售折扣/返利
          stampType: '',
          autoRenewal: 1,
          profitSharingRatio: '',
          contractType: null,
          cooperationMode: null,
          guaranteePrice: null,
          gmvRate: ''
        },
        submitType: 2,
        aduitInfo: {
          countersignSet: 0,
          process: [],
          senders: []
        },
        contractList: [], // 关联合同列表
        accountList: [] // 关联账号列表
      },
      defaultList: {
        'createInfo.proposer': []
      },
      comLegalConstruction: [],
      queryAccountLoading: false
    };
  },
  computed: {
    /* comLegalConstruction() {
      return legalConstruction(this.legalConstructionArg);
    }, */
    rules() {
      const tempRules = JSON.parse(JSON.stringify(this.kolLegalRules));
      const accountPeriodType = this.legalParam.contractInfo.accountPeriod.type;
      if (accountPeriodType === 4) {
        tempRules['contractInfo.accountPeriod.name'][0].required = true;
      } else {
        tempRules['contractInfo.accountPeriod.name'][0].required = false;
      }
      return tempRules;
    },
    isInFeiShu() {
      return getExplorer() === 'Feishu';
    }
  },
  watch: {
    'legalParam.contractInfo.profitSharingRatio': {
      handler(val) {
        const talentNum = !val && val !== 0 ? null : math.subtract(100, Number(val)).toFixed(2);
        this.$set(this.legalParam.contractInfo, 'talentSharingRatio', talentNum);
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    const { signUpId, terminationId, mediumIds } = this.$route.query;
    this.signUpId = signUpId;
    signUpId && this.getSignDetail(signUpId);
    this.comLegalConstruction = JSON.parse(JSON.stringify(legalConstruction(this.legalConstructionArg)));
    if (terminationId && localStorage.getItem('accountsInfoList')) {
      this.formatPlatform();
      this.$set(this.legalParam.contractInfo, 'contractType', 2); // 合同类别默认选中达人解约
    }
    mediumIds && this.setTerminationAccount(mediumIds);
  },
  methods: {
    formatPlatform() { // 处理合作平台/账号字段
      const temp = JSON.parse(localStorage.getItem('accountsInfoList'));
      const len = platformOptions.length;
      const arr = temp.map(item => {
        for (let i = 0; i < len; i++) {
          if (item.platformName === platformOptions[i].label) {
            item.type = platformOptions[i].value;
            break;
          } else {
            item.type = 6; // 其他类型的平台
          }
        }
        return {
          type: item.type,
          account: item.accountName,
          name: item.type === 6 ? item.platformName : ''
        };
      });
      this.legalParam.contractInfo.cooperPlatforms = arr;
      if (this.$route.query.terminationId) {
        this.legalParam.terminationId = this.$route.query.terminationId;
      }
    },
    // 签约内审、解约发起合同，填充对应的关联账号
    setTerminationAccount(ids) {
      const params = {
        page: 1,
        perPage: 0,
        ids,
        idList: ids.split(',')
      };
      this.queryAccountLoading = true;
      getResourceListPost(params).then(res => {
        const accountList = _.cloneDeep(res.data && res.data.items || []); // 关联账号填充
        accountList.forEach(item => {
          item.fansNum = item.baseInfo.fansNum;
          item.signGroupsName = item.additionalKey.signGroupsName;
          item.contractBroker = item.additionalKey.contractBroker;
        });
        this.legalParam.accountList = accountList;
        this.queryAccountLoading = false;
      }).catch(() => {
        this.queryAccountLoading = false;
      });
    },
    getSignDetail(id = '') { // 签约内审详情
      if (!id && id !== 0) return;
      signUpDetail(id).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
        }
        this.initContractData(res.data);
      }).catch((err) => {
        console.log(err);
      });
    },
    initContractData(data) { // 签约内审回填合同信息
      const legalInfo = this.legalParam.contractInfo;
      legalInfo.tempSource = 1;// 模板来源
      legalInfo.subject = 1;// 签约主体
      legalInfo.name = data.channelName || '';// 项目名称
      if (data.supplierType === 0) { // 签约对方，1公司，2个人
        legalInfo.signType = 2;
        legalInfo.oppIdentity = data.accountsReceivable.list.length > 0 && data.accountsReceivable.list[0].identityNumber || '';// 签约对方 身份证，取列表的第一个数据
      } else {
        legalInfo.signType = 1;
      }
      legalInfo.oppCompany = data.channelName || '';// 签约对方 姓名
      if (data.accountsInfoList && data.accountsInfoList.length !== 0) { // 存在账号
        const accountLegalInfo = data.accountsInfoList[0].contractInfo;// 账号合同信息
        const accountPriceInfo = data.accountsInfoList[0].priceInfo;// 价格信息
        const priceDynamic = accountPriceInfo.dynamicKey;
        if (accountLegalInfo.signStartDate) {
          // 合同期限为达人的签约日期
          legalInfo.deadline = [accountLegalInfo.signStartDate, accountLegalInfo.signEndDate];
        }
        legalInfo.autoRenewal = typeof accountLegalInfo.autoRenewal === 'number' ? accountLegalInfo.autoRenewal : 1;// 自动续约
        if (priceDynamic) {
          // 价格信息-返点方式为无: 折扣返利为无; 累量返点,独立返点5%,独立返点10%: 有
          for (let i = 0; i < priceDynamic.length; i++) {
            if (priceDynamic[i].name === '返点方式') {
              const temp = priceDynamic[i].options.filter(item => {
                return item.value === priceDynamic[i].value;
              });
              if (temp[0].label === '无') {
                legalInfo.rebates = 0;
              } else if (['累量返点', '独立返点5%', '独立返点10%'].includes(temp[0].label)) {
                legalInfo.rebates = 1;
              }
              break;
            }
          }
        }
        const platformArr = ['微信', '微博', '小红书', '抖音', 'B站'];// 1-5,其他平台都属于其他, 6为其他
        data.accountsInfoList && data.accountsInfoList.forEach(el => { // 账号回填
          const isOther = !!(platformArr.indexOf(el.accountsInfo.platformName) === -1);
          const accountObj = {
            type: isOther ? 6 : plateformType(el.accountsInfo.platformName),
            account: el.accountsInfo.accountName
          };
          if (isOther) {
            accountObj.name = el.accountsInfo.platformName;
          }
          legalInfo.cooperPlatforms.push(accountObj);
        });
        legalInfo.cooperPlatforms.shift();// 去掉默认的第一条空数据
        if (accountPriceInfo) {
          if (accountPriceInfo.profitSharingRemark) { // 分成说明
            legalInfo.earnings.proportion = accountPriceInfo.profitSharingRemark;
          }
          if (accountPriceInfo.guaranteeRemark) { // 保底说明
            legalInfo.earnings.earningTypes.push(2);
            legalInfo.earnings.guaranteeSum = accountPriceInfo.guaranteeRemark;
          }
          if (accountPriceInfo.profitSharingRatio || accountPriceInfo.profitSharingRatio === 0) { // 分成比例
            this.$set(legalInfo, 'profitSharingRatio', accountPriceInfo.profitSharingRatio);
            this.$set(legalInfo, 'talentSharingRatio', math.subtract(100, legalInfo.profitSharingRatio));
          }
          if (accountPriceInfo.guaranteePrice || accountPriceInfo.guaranteePrice === 0) { // 保底金额
            this.$set(legalInfo, 'guaranteePrice', accountPriceInfo.guaranteePrice);
          }
        }
        if (accountLegalInfo && (accountLegalInfo.cooperation || accountLegalInfo.cooperation === 0)) { // 合作方式
          this.$set(legalInfo, 'cooperationMode', accountLegalInfo.cooperation);
        }
        this.$set(legalInfo, 'contractType', 1); // 合同类别默认选中签约内审
      }
    },
    submitFun(senders = []) {
      this.modifySenders = senders;// 存到mixins
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 600) {
        return;
      }
      this.antiShakeTime = timestamp;
      if (this.isSubmit) return;
      const params = JSON.parse(JSON.stringify(this.legalParam));
      if (this.reapplyId) {
        params.submitType = 3;
        params.byReapplyId = this.legalId;
      } else {
        params.submitType = 2;
        if (params.hasOwnProperty('byReapplyId')) delete params.byReapplyId;
      }
      this.remodifyId && (params.byRemodifyId = this.remodifyId);
      params.orders = this.orderPriceSwitch(this.orders, 2);
      delete params.createInfo.creater;
      delete params.createInfo.createrDepartment;
      delete params.createInfo.proposer;
      if (params.contractInfo.earnings.earningTypes.indexOf(1) < 0) {
        delete params.contractInfo.earnings.proportion;
      }
      if (params.contractInfo.earnings.earningTypes.indexOf(2) < 0) {
        delete params.contractInfo.earnings.guaranteeSum;
      }
      if (this.isSigner === 0) {
        params.aduitInfo = this.removeSigner(params.aduitInfo);
      }
      const message = (this.legalId && !this.createNew && !this.setSaveDraftStatus()) ? '合同修改成功' : '合同新建成功';
      if (this.$route.query.signUpId) {
        params.signUpId = Number(this.$route.query.signUpId);
      }
      if (this.legalId && !this.createNew) {
        this.handleModifyData(params);
      }
      this.handlePost(params, message);
    },
    toSignUpDetail() {
      this.$router.push({
        name: 'signUpDetail',
        query: {
          signUpId: this.$route.query.signUpId,
          processId: this.$route.query.processId,
          fromList: 1
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.legal-wrap {
  .footer-btn-wrap {
    display: flex;
    justify-content: center;
  }
  .module-box {
    // margin-bottom: 40px;
    padding-bottom: 32px;
  }
}
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  width: 80px;
  padding: 7px 0;
  text-align: center;
}
::v-deep .el-form-item__error {
  padding-top: 2px !important;
}
</style>
